<?php
/**
 * FastApp.
 * 8/18/24
 * @Author 深色的海 (wx:deepsea_0024)
 * @Contact telegram:deepsea159
 */

namespace App\Marketing\Api\Service;

use App\Fastapp\Api\Service\Account\WalletService;
use App\Fastapp\Model\AccountWalletLog;
use App\Marketing\Model\MarketingTask;
use App\Marketing\Model\MarketingTaskLog;

class TaskService
{
    public function list(string $code): array
    {
        $res = MarketingTask::query()
            ->select(['id', 'name', 'title', 'icon', 'amount', 'refunded', 'type'])
            ->where(['code' => $code, 'status' => 1, 'account_type' => fastapp_header('account-type')])
            ->orderByDesc('sort')->get()->map(function ($item) {
                $item->name = fastapp_lang_text($item->name);
                $item->title = fastapp_lang_text($item->title);
                return $item;
            });
        $list = $log = [];
        try {
            $log = MarketingTaskLog::query()->where(['user_id' => get_uid()])
                ->whereIn('task_id', $res->pluck('id')->toArray())
                ->get(['get_at', 'task_id', 'id'])->mapWithKeys(function ($item) {
                    return [$item->task_id => $item];
                })->toArray();
        } catch (\Throwable) {
        }
        foreach ($res as $item) {
            $item->complete = isset($log[$item->id]) ? 1 : 0;
            $item->get_at = $log[$item->id]['get_at'] ?? '';
            $item->log_id = $log[$item->id]['id'] ?? 0;
            $list[] = $item;
        }
        return ['list' => $list];
    }

    public function getRefunded(int $id): void
    {
        $uid = get_uid();
        $md = MarketingTaskLog::query()->with(['task:id,refunded'])->whereNull('get_at')->where(['user_id' => $uid])->findOrFail($id);
        WalletService::inc([
            'user_id' => $uid,
            'amount' => $md->task->refunded,
            'symbol' => get_user_cache('symbol', $uid),
            'type' => AccountWalletLog::RECHARGE,
            'object_type' => AccountWalletLog::OBJ_TYPE_TASK_LOG,
            'object_id' => $id
        ]);
        $md->update(['get_at' => date('Y-m-d H:i:s')]);
    }
}